//
//  QBAssetsCollectionViewController.m
//  QBImagePickerController
//
//  Created by Tanaka Katsuma on 2013/12/31.
//  Copyright (c) 2013年 Katsuma Tanaka. All rights reserved.
//

#import "QBAssetsCollectionViewController.h"

// Views
#import "QBAssetsCollectionViewCell.h"
#import "QBAssetsCollectionFooterView.h"

#import "QBMFImagePrviewViewController.h"

@interface QBAssetsCollectionViewController ()
{
    UIBarButtonItem *previewItem;
    UIBarButtonItem *selectedItem;
    UIBarButtonItem *doneItem;
}

@property (nonatomic, assign) NSInteger numberOfPhotos;

@end

@implementation QBAssetsCollectionViewController

- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout
{
    self = [super initWithCollectionViewLayout:layout];
    
    if (self) {
        // View settings
        self.view.backgroundColor = [UIColor whiteColor];
        
        self.collectionView.backgroundColor = [UIColor whiteColor];
        self.collectionView.allowsMultipleSelection = YES;
        self.collectionView.frame = CGRectMake(self.collectionView.frame.origin.x, self.collectionView.frame.origin.y, self.collectionView.frame.size.width, self.collectionView.frame.size.height-44);
        
        UIToolbar *assetsToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-44+self.view.frame.origin.y, self.view.frame.size.width, 44)];
        [self.view addSubview:assetsToolBar];
        NSMutableArray *items = [[NSMutableArray alloc] init];
        previewItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedStringFromTable(@"preview", @"QBImagePickerController", nil) style:UIBarButtonItemStyleDone target:self action:@selector(preview:)];
        [items addObject:previewItem];
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [items addObject:flexSpace];
        selectedItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
        [items addObject:selectedItem];
        flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [items addObject:flexSpace];
        doneItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedStringFromTable(@"done", @"QBImagePickerController", nil) style:UIBarButtonItemStyleDone target:self.navigationController action:@selector(toolbarDone)];
        [items addObject:doneItem];
        [assetsToolBar setItems:items];
        
        UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self.navigationController action:@selector(imagePickerCancel)];
        [self.navigationItem setRightBarButtonItem:cancelButton animated:NO];
        
        // Register cell class
        [self.collectionView registerClass:[QBAssetsCollectionViewCell class]
                forCellWithReuseIdentifier:@"AssetsCell"];
        [self.collectionView registerClass:[QBAssetsCollectionFooterView class]
                forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                       withReuseIdentifier:@"FooterView"];
    }
    
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // Scroll to bottom
    CGFloat topInset = ((self.edgesForExtendedLayout && UIRectEdgeTop) && (self.collectionView.contentInset.top == 0)) ? (20.0 + 44.0) : 0.0;
    
    [self.collectionView setContentOffset:CGPointMake(0, self.collectionView.collectionViewLayout.collectionViewContentSize.height - self.collectionView.frame.size.height + topInset)
                                 animated:NO];
    
    [self updateToolBarContent];
    
    
}

-(void)toolbarDone
{
    [((QBMFImagePickerController *)self.navigationController) imagePickerFinish:nil];
}

- (void)preview:(id)sender
{
    //预览
    //do...
    QBMFImagePrviewViewController *qbmfPrviewController = [[QBMFImagePrviewViewController alloc] init];
    [self.navigationController pushViewController:qbmfPrviewController animated:YES];
//    qbmfPrviewController.selectedAssets = [NSMutableArray array];
//    __block QBMFImagePickerController *QBMFController = ((QBMFImagePickerController *)self.navigationController);
//    for (NSURL *selectedAssetURL in QBMFController.selectedAssetURLs) {
//        [QBMFController.assetsLibrary assetForURL:selectedAssetURL
//                                      resultBlock:^(ALAsset *asset) {
//                                          // Add asset
//                                          ALAssetRepresentation *rep = [asset defaultRepresentation];
//                                          [qbmfPrviewController.selectedAssets addObject:[UIImage imageWithCGImage:[rep fullScreenImage]]];
//                                          if ([QBMFController.selectedAssetURLs count] == [qbmfPrviewController.selectedAssets count]) {
//                                              
//                                              [self.navigationController pushViewController:qbmfPrviewController animated:YES];
//                                          }
//                                          
//                                      } failureBlock:^(NSError *error) {
//                                          
//                                      }];
//    }
    
}

-(void)updateToolBarContent
{
    QBMFImagePickerController *QBMFController = ((QBMFImagePickerController *)self.navigationController);
    
    previewItem.enabled = (QBMFController.selectedAssetURLs.count>0);
    doneItem.enabled = previewItem.enabled;
    selectedItem.title = [NSString stringWithFormat:NSLocalizedStringFromTable(@"selected_photos_and_maxphotos",@"QBImagePickerController", nil),QBMFController.selectedAssetURLs.count,QBMFController.maximumNumberOfSelection];
}

- (void)setAssetsGroup:(ALAssetsGroup *)assetsGroup
{
    _assetsGroup = assetsGroup;
    
    // Set title
    self.title = [self.assetsGroup valueForProperty:ALAssetsGroupPropertyName];
    
    // Get the number of photos and videos
    [self.assetsGroup setAssetsFilter:ALAssetsFilterFromQBImagePickerControllerFilterType(((QBMFImagePickerController *)self.navigationController).filterType)];
    self.numberOfPhotos = self.assetsGroup.numberOfAssets;
    
    // Load assets
    self.assets = [NSMutableArray array];
    
    __weak typeof(self) weakSelf = self;
    [self.assetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if (result) {
            [weakSelf.assets addObject:result];
        }
    }];
    
    // Update view
    [self.collectionView reloadData];
}

#pragma mark - Managing Selection
- (void)selectAssetHavingURL:(NSURL *)URL
{
    for (NSInteger i = 0; i < self.assets.count; i++) {
        ALAsset *asset = [self.assets objectAtIndex:i];
        NSURL *assetURL = [asset valueForProperty:ALAssetPropertyAssetURL];
        
        if ([assetURL isEqual:URL]) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
            
            return;
        }
    }
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.assetsGroup.numberOfAssets;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    QBAssetsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AssetsCell" forIndexPath:indexPath];
    cell.showsOverlayViewWhenSelected = YES;
    
    ALAsset *asset = [self.assets objectAtIndex:indexPath.row];
    cell.asset = asset;
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(collectionView.bounds.size.width, 46.0);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionFooter) {
        QBAssetsCollectionFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                                                                      withReuseIdentifier:@"FooterView"
                                                                                             forIndexPath:indexPath];
        
        footerView.textLabel.text = [NSString stringWithFormat:NSLocalizedStringFromTable(@"format_photos",
                                                                                          @"QBImagePickerController",
                                                                                          nil),
                                     self.numberOfPhotos
                                     ];
        return footerView;
    }
    
    return nil;
}


#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(77.5, 77.5);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(2, 2, 2, 2);
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return (((QBMFImagePickerController *)self.navigationController).selectedAssetURLs.count+1 <= ((QBMFImagePickerController *)self.navigationController).maximumNumberOfSelection);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    QBMFImagePickerController *QBMFController = ((QBMFImagePickerController *)self.navigationController);
    
    ALAsset *asset = [self.assets objectAtIndex:indexPath.row];
 
    NSURL *assetURL = [asset valueForProperty:ALAssetPropertyAssetURL];
    [QBMFController.selectedAssetURLs addObject:assetURL];
    
    [self updateToolBarContent];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    QBMFImagePickerController *QBMFController = ((QBMFImagePickerController *)self.navigationController);
    
    ALAsset *asset = [self.assets objectAtIndex:indexPath.row];
   
    NSURL *assetURL = [asset valueForProperty:ALAssetPropertyAssetURL];
    [QBMFController.selectedAssetURLs removeObject:assetURL];
    
    [self updateToolBarContent];
    
}

@end
